package vn.huync.smsbackupandrestore;

import java.util.ArrayList;
import java.util.Iterator;

import vn.huync.smsbackupandrestore.models.ContactModel;
import vn.huync.smsbackupandrestore.models.SmsModel;
import vn.huync.smsbackupandrestore.others.Utils;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.PhoneNumberUtils;
import android.text.Html;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.nch.smsbackupandrestore.R;

public class ListSmsByAddressActivity extends ListActivity {
	MyApp myApp;
	ArrayList<SmsModel> lSmsLastest, lSmsReadFromSdcard;
	ListSmsAdapter adapter;
	ListView lv;
	String filePath;
	
	final int CALL_THIS_NUMBER_MENU_ITEM = 0;
	final int SEND_SMS_MENU_ITEM = 1;
	final int DELETE_SMS_MENU_ITEM = 2;
	final int RESTORE_MENU_ITEM = 3;
	
	ProgressDialog progressDialog;
	
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			int numSmsRestored = msg.getData().getInt("numSmsRestored");
			progressDialog.setProgress(numSmsRestored);
			if(progressDialog.getProgress() == progressDialog.getMax()){
				progressDialog.dismiss();
				Utils.ShowToast(ListSmsByAddressActivity.this, 
						numSmsRestored + " " + getString(R.string.sms_has_been_restored));
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_simple);
		
		myApp = (MyApp)getApplicationContext();
		
		lSmsLastest = new ArrayList<SmsModel>();
		filePath = getIntent().getExtras().getString("filePath");
		
		Thread readSmsThread = new Thread(new Runnable() {
			
			public void run() {
				lSmsReadFromSdcard = Utils.ReadSmsFromSDCardToList(filePath);
				Utils.GetListLastestSmsByAddress(lSmsReadFromSdcard, lSmsLastest);
				adapter = new ListSmsAdapter(getApplicationContext(), R.layout.list_simple, lSmsLastest, myApp.lContact);
				runOnUiThread(new Runnable() {
					
					public void run() {
						setListAdapter(adapter);
					}
				});
			}
		});
		readSmsThread.start();
		
		registerForContextMenu(getListView());
		lv = getListView();
		
		AdView adView = (AdView)this.findViewById(R.id.adView);
	    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
	    adRequestBuilder.addTestDevice("EEB3EC34691D85EFD1DF789EA3776326");
	    adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
	    AdRequest adRequest = adRequestBuilder.build();
	    adView.loadAd(adRequest);
	}
	
	class ListSmsAdapter extends ArrayAdapter<SmsModel>{
		Context context;
		int textViewResourceId;
		ArrayList<SmsModel> objects;
		ArrayList<ContactModel> contacts;
		public ListSmsAdapter(Context context, int textViewResourceId,
				ArrayList<SmsModel> objects, ArrayList<ContactModel> contacts) {
			super(context, textViewResourceId, objects);
			this.context = context;
			this.textViewResourceId = textViewResourceId;
			this.objects = objects;
			this.contacts = contacts;
		}
		
		void SetData(ArrayList<SmsModel> objects){
			this.objects = objects;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if(row == null){
				LayoutInflater inflater = LayoutInflater.from(ListSmsByAddressActivity.this);
				row = inflater.inflate(R.layout.row_sms_list, null);
			}
			
			TextView tAddress = (TextView) row.findViewById(R.id.row_address);
			TextView tContent = (TextView) row.findViewById(R.id.row_content);
			
			SmsModel sms = objects.get(position);
			String address = Utils.GetDisplayNameOfSms(sms, contacts);
			if(address != "") address += " ";
			address += "&lt;" + sms.getAddress() + "&gt;";
			String body = sms.getBody();
			if(body.length() > 160) body = body.substring(0, 160) + " ...";
			tAddress.setText(Html.fromHtml("<b>" + address + "</b>"));
			tContent.setText(body);
			
			return row;
		}
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		Intent intent = new Intent(this, ListSmsActivity.class);
		intent.putExtra("address", lSmsLastest.get(position).getAddress());
		intent.putParcelableArrayListExtra("smsRead", lSmsReadFromSdcard);
		intent.putExtra("filePath", filePath);
		startActivity(intent);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, CALL_THIS_NUMBER_MENU_ITEM, CALL_THIS_NUMBER_MENU_ITEM, R.string.call_this_contact);
		menu.add(Menu.NONE, SEND_SMS_MENU_ITEM, SEND_SMS_MENU_ITEM, R.string.send_sms_to_this_contact);
		menu.add(Menu.NONE, DELETE_SMS_MENU_ITEM, DELETE_SMS_MENU_ITEM, R.string.delete_all_contact_backup_message);
		menu.add(Menu.NONE, RESTORE_MENU_ITEM, RESTORE_MENU_ITEM, R.string.restore_this_contact_message);
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo adapterInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		SmsModel smsSelected = lSmsLastest.get(adapterInfo.position);
		switch(item.getItemId())
		{
		case CALL_THIS_NUMBER_MENU_ITEM:
			Intent callIntent = new Intent(Intent.ACTION_DIAL);
			callIntent.setData(Uri.parse("tel:"+smsSelected.getAddress()));
			startActivity(callIntent);
			break;
		case SEND_SMS_MENU_ITEM:
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("sms:"
                    + smsSelected.getAddress())));
			break;
		case DELETE_SMS_MENU_ITEM:
			String addressSelected = smsSelected.getAddress();
			for(Iterator<SmsModel> i = lSmsReadFromSdcard.iterator(); i.hasNext();){
				SmsModel sms = i.next();
				if(PhoneNumberUtils.compare(sms.getAddress(), addressSelected) == true){
					i.remove();
				}
			}
			Utils.WriteFromListToXML(filePath, lSmsReadFromSdcard, null);
			Utils.GetListLastestSmsByAddress(lSmsReadFromSdcard, lSmsLastest);
			adapter.remove(smsSelected);
			adapter.notifyDataSetChanged();
			break;
		case RESTORE_MENU_ITEM:
			final ArrayList<SmsModel> smsNeedWriteToDb = new ArrayList<SmsModel>();
			addressSelected = smsSelected.getAddress();
			for(SmsModel sms:lSmsReadFromSdcard){
				if(PhoneNumberUtils.compare(sms.getAddress(), addressSelected) == true){
					smsNeedWriteToDb.add(sms);
				}
			}
			SmsModel.deleteSmsExistInDbFromArray(getApplicationContext(), smsNeedWriteToDb);
			if(smsNeedWriteToDb.size() > 0){
				showProgressBar(smsNeedWriteToDb.size());
				Thread restoreThread = new Thread(new Runnable() {
					
					public void run() {
						Utils.WriteSmsFromListToDb(ListSmsByAddressActivity.this, smsNeedWriteToDb, handler);
					}
				});
				restoreThread.start();
			}
			else Utils.ShowToast(ListSmsByAddressActivity.this, 
					0 + " " + getString(R.string.sms_has_been_restored));
		}
		return super.onContextItemSelected(item);
	}
	
	void showProgressBar(int max){
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(false);
		progressDialog.setMessage(getString(R.string.restoring));
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setProgress(0);
		progressDialog.setMax(max);
		progressDialog.show();
	}
}
